package pro2;
import pro3.UserVO;
import java.io.IOException;
import java.security.MessageDigest;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Ans2/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        // 获取表单数据
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String gender = request.getParameter("gender");
        String city = request.getParameter("city");
        // 处理性别字段
        if ("男".equals(gender)) {
            gender = "male";
        } else if ("女".equals(gender)) {
            gender = "female";
        } else {
            session.setAttribute("error", "请选择性别");
            response.sendRedirect(request.getContextPath() + "/Ans2/registerResult.jsp");
            return;
        }
        // 密码加密（MD5）
        String encryptedPassword = md5(password);

        // 使用 UserVO 封装用户信息
        UserVO user = new UserVO();
        user.setEmail(email);
        user.setPassword(encryptedPassword);
        user.setGender(gender);
        user.setCity(city);

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/cwl_db", "root", "123456"
            );

            // 检查邮箱是否已存在
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM cwl_user WHERE email = ?");
            stmt.setString(1, user.getEmail());
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                session.setAttribute("error", "邮箱已存在");
                response.sendRedirect(request.getContextPath() + "/Ans2/registerResult.jsp");
            } else {
                // 插入新用户
                stmt = conn.prepareStatement("INSERT INTO cwl_user (email, password, gender, city) VALUES (?, ?, ?, ?)");
                stmt.setString(1, user.getEmail());
                stmt.setString(2, user.getPassword());
                stmt.setString(3, user.getGender());
                stmt.setString(4, user.getCity());
                int rows = stmt.executeUpdate();
                System.out.println("插入新用户，影响行数：" + rows);

                session.setAttribute("success", "注册成功，请登录！");
                response.sendRedirect(request.getContextPath() + "/Ans2/registerResult.jsp");
            }

            rs.close();
            stmt.close();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("error", "注册失败，请重试");
            response.sendRedirect(request.getContextPath() + "/Ans2/registerResult.jsp");
        }
    }

    // MD5 加密方法
    public static String md5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : messageDigest) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
